package com.superlc.ssm.core.shiro.filter;

import com.superlc.ssm.common.util.ProjectUtils;
import com.superlc.ssm.common.util.ResponseUtils;
import com.superlc.ssm.core.shiro.ShiroConst;
import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author super
 * 自定义的rolefilter,ajax请求不重定向
 */
public class ShiroRolesAuthorizationFilter extends RolesAuthorizationFilter {
    private static Logger logger = LoggerFactory.getLogger(ShiroRolesAuthorizationFilter.class);


    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {

        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse resp = (HttpServletResponse) response;
        if(req.getMethod().equals(RequestMethod.OPTIONS.name())) {
            resp.setStatus(HttpStatus.OK.value());
            return true;
        }
        //前端Ajax请求时requestHeader里面带一些参数，用于判断是否是前端的请求
        String ajaxHeader = req.getHeader(ShiroConst.AUTHORIZATION);
        if (ajaxHeader != null || req.getHeader("wkcheck") != null) {
            logger.info("当前请求为ajax请求不会重定向！");
            //前端Ajax请求，则不会重定向
            resp.setHeader("Access-Control-Allow-Origin",  req.getHeader("Origin"));
            resp.setHeader("Access-Control-Allow-Credentials", "true");
            resp.setContentType("application/json; charset=utf-8");
            resp.setCharacterEncoding("UTF-8");
            PrintWriter out = resp.getWriter();
            ProjectUtils.object2Json(ResponseUtils.failed("ajax请求无权限！"),out);
            return false;
        }
        return super.onAccessDenied(request, response);
    }
}
